/**
 * 文件管理页面 V2 - 使用全局axios封装
 * 功能：文件上传（支持大文件）、文件列表（多种视图）、文件预览、文件分享、批量操作
 */
import React, { useState, useEffect, useRef, useCallback } from 'react';
import SparkMD5 from 'spark-md5';
import { fileManagerAPI, FileItem, ShareConfig, ShareResult } from '../../utils/api';
import { 
  saveUploadProgress, 
  getUploadProgress, 
  updateUploadedChunk, 
  removeUploadProgress,
  cleanExpiredProgress 
} from '../../utils/upload/uploadProgress';
import { ACTION_PERMISSION_CODES } from '@/config/actionPermissions';
import { Permission } from '@/utils/permission/usePermission';
import { useThemeStore } from '@/stores/themeStore';

// 上传进度
interface UploadProgress {
  filename: string;
  progress: number;
  status: 'uploading' | 'success' | 'error' | 'paused';
  message?: string;
  hash?: string; // 用于暂停/继续控制
  chunkInfo?: string; // 分片信息，如 "3/10 分片"
  isResuming?: boolean; // 是否正在续传
}

// 视图模式
type ViewMode = 'grid' | 'list';

// 提取视频第一帧作为封面（从File对象）
const extractVideoThumbnail = (videoFile: File): Promise<Blob> => {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    video.preload = 'metadata';
    video.muted = true; // 静音，避免播放声音
    video.playsInline = true; // 内联播放
    
    // 创建视频URL
    const videoUrl = URL.createObjectURL(videoFile);
    video.src = videoUrl;
    
    // 等待视频元数据加载完成
    video.onloadeddata = () => {
      try {
        // 设置视频时间到第一帧（0.1秒，避免黑屏）
        video.currentTime = 0.1;
      } catch (error) {
        console.warn('设置视频时间失败，使用默认时间:', error);
        video.currentTime = 0;
      }
    };
    
    // 当视频跳转到指定时间后
    video.onseeked = () => {
      try {
        // 创建Canvas
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth || 320;
        canvas.height = video.videoHeight || 240;
        const ctx = canvas.getContext('2d');
        
        if (!ctx) {
          reject(new Error('无法创建Canvas上下文'));
          URL.revokeObjectURL(videoUrl);
          return;
        }
        
        // 将视频帧绘制到Canvas
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // 将Canvas转换为Blob
        canvas.toBlob((blob) => {
          URL.revokeObjectURL(videoUrl); // 清理URL
          if (blob) {
            console.log('✅ 视频封面提取成功，大小:', blob.size, 'bytes');
            resolve(blob);
          } else {
            reject(new Error('Canvas转换为Blob失败'));
          }
        }, 'image/jpeg', 0.8); // JPEG格式，质量0.8
      } catch (error) {
        URL.revokeObjectURL(videoUrl);
        reject(error);
      }
    };
    
    video.onerror = () => {
      URL.revokeObjectURL(videoUrl);
      reject(new Error('视频加载失败'));
    };
    
    // 如果视频无法加载，设置一个超时
    setTimeout(() => {
      if (video.readyState < 2) { // HAVE_CURRENT_DATA
        URL.revokeObjectURL(videoUrl);
        reject(new Error('视频加载超时'));
      }
    }, 10000); // 10秒超时
  });
};

// 从URL提取视频封面（用于大文件合并后）
const extractVideoThumbnailFromUrl = (videoUrl: string): Promise<Blob> => {
  return new Promise((resolve, reject) => {
    const video = document.createElement('video');
    video.preload = 'metadata';
    video.muted = true;
    video.playsInline = true;
    video.crossOrigin = 'anonymous'; // 允许跨域
    
    // 等待视频元数据加载完成
    video.onloadeddata = () => {
      try {
        // 设置视频时间到第一帧（0.1秒，避免黑屏）
        video.currentTime = 0.1;
      } catch (error) {
        console.warn('设置视频时间失败，使用默认时间:', error);
        video.currentTime = 0;
      }
    };
    
    // 当视频跳转到指定时间后
    video.onseeked = () => {
      try {
        // 创建Canvas
        const canvas = document.createElement('canvas');
        canvas.width = video.videoWidth || 320;
        canvas.height = video.videoHeight || 240;
        const ctx = canvas.getContext('2d');
        
        if (!ctx) {
          reject(new Error('无法创建Canvas上下文'));
          return;
        }
        
        // 将视频帧绘制到Canvas
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        
        // 将Canvas转换为Blob
        canvas.toBlob((blob) => {
          if (blob) {
            console.log('✅ 视频封面提取成功（从URL），大小:', blob.size, 'bytes');
            resolve(blob);
          } else {
            reject(new Error('Canvas转换为Blob失败'));
          }
        }, 'image/jpeg', 0.8);
      } catch (error) {
        reject(error);
      }
    };
    
    video.onerror = () => {
      reject(new Error('视频加载失败'));
    };
    
    // 设置超时
    setTimeout(() => {
      if (video.readyState < 2) {
        reject(new Error('视频加载超时'));
      }
    }, 10000);
    
    video.src = videoUrl;
  });
};


// 文件分类
const FILE_CATEGORIES = [
  { value: 'all', label: '全部文件', icon: '📁' },
  { value: 'image', label: '图片', icon: '🖼️' },
  { value: 'video', label: '视频', icon: '🎬' },
  { value: 'audio', label: '音频', icon: '🎵' },
  { value: 'document', label: '文档', icon: '📄' },
  { value: 'other', label: '其他', icon: '📦' }
];

// 动态分片大小（单位：Byte）
const MB = 1024 * 1024;
const getDynamicChunkSize = (fileSize: number): number => {
  if (fileSize <= 50 * MB) {
    return 2 * MB;
  }
  if (fileSize <= 200 * MB) {
    return 5 * MB;
  }
  if (fileSize <= 1024 * MB) {
    return 10 * MB;
  }
  return 20 * MB;
};

const FileManager: React.FC = () => {
  const themeStore = useThemeStore();
  const isDark = themeStore.getEffectiveTheme() === 'dark';
  // 状态管理
  const [files, setFiles] = useState<FileItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [viewMode, setViewMode] = useState<ViewMode>('grid');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [keyword, setKeyword] = useState('');
  const [selectedFiles, setSelectedFiles] = useState<Set<string>>(new Set());
  const [uploadProgress, setUploadProgress] = useState<UploadProgress[]>([]);
  const [previewFile, setPreviewFile] = useState<FileItem | null>(null);
  const [shareModalFile, setShareModalFile] = useState<FileItem | null>(null);
  const [shareConfig, setShareConfig] = useState<ShareConfig>({
    expireDays: 7,
    password: '',
    downloadLimit: 0
  });
  const [shareResult, setShareResult] = useState<ShareResult | null>(null);
  
  const fileInputRef = useRef<HTMLInputElement>(null);
  const dragRef = useRef<HTMLDivElement>(null);
  const pausedUploadsRef = useRef<Set<string>>(new Set()); // 使用 ref 存储暂停状态，避免闭包问题

  // ✅ 收藏文件
  const toggleFavorite = async (fileId: string, isFavorite: boolean) => {
    try {
      if (isFavorite) {
        await fileManagerAPI.unfavoriteFile(fileId);
      } else {
        await fileManagerAPI.favoriteFile(fileId);
      }
      loadFiles();
    } catch (error) {
      console.error('收藏操作失败:', error);
    }
  };


  // 加载文件列表
  const loadFiles = useCallback(async () => {
    setLoading(true);
    try {
      const params = { page: 1, limit: 100, category: selectedCategory !== 'all' ? selectedCategory : undefined, keyword: keyword || undefined };

      const response = await fileManagerAPI.getFiles(params);
      if (response.success) {
        setFiles(response.data.files);
      }
    } catch (error) {
      console.error('加载文件列表失败:', error);
      const message = error instanceof Error ? error.message : '加载文件列表失败';
      alert(message);
    } finally {
      setLoading(false);
    }
  }, [selectedCategory, keyword]);

  useEffect(() => {
    loadFiles();
    // 清理过期的上传进度记录
    cleanExpiredProgress();
  }, [loadFiles]);

  // 处理文件上传
  const handleFileUpload = async (fileList: FileList) => {
    const files = Array.from(fileList);
    const LARGE_FILE_THRESHOLD = 10 * 1024 * 1024; // 10MB以上使用切片上传

    for (const file of files) {
      // 计算文件hash用于标识
      console.log(`📝 开始处理文件: ${file.name}, 大小: ${(file.size / 1024 / 1024).toFixed(2)}MB`);
      const tempHash = await calculateFileHash(file);
      console.log(`🔑 文件hash计算完成: ${tempHash}`);
      
      const progressItem: UploadProgress = {
        filename: file.name,
        progress: 0,
        status: 'uploading',
        hash: tempHash
      };
      setUploadProgress(prev => [...prev, progressItem]);

      try {
        if (file.size > LARGE_FILE_THRESHOLD) {
          // 大文件切片上传
          await uploadLargeFile(file, tempHash, (progress) => {
            updateProgress(file.name, progress);
          });
        } else {
          // 普通文件上传
          await uploadNormalFile(file, (progress) => {
            updateProgress(file.name, progress);
          });
        }
        
        updateProgress(file.name, 100, 'success', '上传成功');
      } catch (error) {
        console.error('上传失败:', error);
        const message = error instanceof Error ? error.message : '上传失败';
        // 如果是暂停导致的，标记为暂停状态
        if (message.includes('用户暂停')) {
          updateProgress(file.name, undefined, 'paused', '已暂停');
        } else {
          updateProgress(file.name, 0, 'error', message);
        }
      }
    }

    // 刷新文件列表
    setTimeout(() => {
      loadFiles();
      setUploadProgress(prev => prev.filter(p => p.status === 'paused')); // 保留暂停的任务
    }, 2000);
  };

  // 普通文件上传
  const uploadNormalFile = async (file: File, onProgress: (progress: number) => void) => {
    const formData = new FormData();
    formData.append('files', file);
    formData.append('userId', 'user123');
    formData.append('userName', '测试用户');

    // 如果是视频文件，提取封面并上传
    let thumbnailUrl: string | null = null;
    if (file.type.startsWith('video/')) {
      try {
        console.log('🎬 开始提取视频封面:', file.name);
        const thumbnailBlob = await extractVideoThumbnail(file);
        
        // 将封面作为文件上传（标记为封面，不显示在文件列表中）
        const thumbnailFile = new File([thumbnailBlob], `thumb-${file.name}.jpg`, { type: 'image/jpeg' });
        const thumbnailFormData = new FormData();
        thumbnailFormData.append('files', thumbnailFile);
        thumbnailFormData.append('userId', 'user123');
        thumbnailFormData.append('userName', '测试用户');
        thumbnailFormData.append('isThumbnail', 'true'); // 标记为封面文件
        
        const thumbnailResponse = await fileManagerAPI.upload(thumbnailFormData);
        if (thumbnailResponse.success && thumbnailResponse.data && thumbnailResponse.data.length > 0) {
          thumbnailUrl = thumbnailResponse.data[0].url;
          console.log('✅ 视频封面上传成功:', thumbnailUrl);
        }
      } catch (error) {
        console.warn('⚠️ 视频封面提取/上传失败:', error);
        // 封面提取失败不影响视频上传，继续上传视频
      }
    }

    // 如果有封面，将封面URL一起传递
    if (thumbnailUrl) {
      formData.append('thumbnailUrl', thumbnailUrl);
    }

    await fileManagerAPI.upload(formData, onProgress);
  };

  // 大文件切片上传（支持断点续传）
  const uploadLargeFile = async (file: File, hash: string, onProgress: (progress: number) => void) => {
    const chunkSize = getDynamicChunkSize(file.size);
    console.log(`📦 使用动态分片大小: ${(chunkSize / MB).toFixed(1)} MB (${chunkSize} bytes)`);
    
    // 显示计算进度
    onProgress(5);
    
    // 检查文件是否已存在（秒传）
    try {
      const checkRes = await fileManagerAPI.checkHash(hash);
      const checkData = checkRes.data || checkRes;
      if (checkData.exists) {
        console.log('✅ 秒传成功：文件已存在');
        removeUploadProgress(hash); // 清理进度记录
        onProgress(100);
        return;
      }
    } catch {
      console.log('秒传检查失败，继续正常上传');
    }

    // 切片上传
    const totalChunks = Math.ceil(file.size / chunkSize);
    let uploadedChunksList: number[] = [];

    // 🔥 断点续传：优先查询服务器已上传的分片（最准确）
    let isResuming = false;
    try {
      const checkChunksRes = await fileManagerAPI.checkChunks(hash);
      const chunksData = checkChunksRes.data || checkChunksRes;
      if (chunksData.uploadedChunks && chunksData.uploadedChunks.length > 0) {
        console.log(`☁️ 服务器已有 ${chunksData.uploadedChunks.length}/${totalChunks} 个分片`);
        uploadedChunksList = chunksData.uploadedChunks;
        isResuming = true;
        // 更新进度显示：显示断点续传提示
        const resumeProgress = Math.round((uploadedChunksList.length / totalChunks) * 90);
        onProgress(resumeProgress);
        updateProgress(file.name, resumeProgress, 'uploading', 
          `🔄 断点续传：已检测到 ${uploadedChunksList.length}/${totalChunks} 个分片，继续上传...`,
          `${uploadedChunksList.length}/${totalChunks} 分片`, true);
      }
    } catch {
      console.log('查询服务器分片失败，检查本地记录');
      
      // 服务器查询失败时，才使用本地记录
      const localProgress = getUploadProgress(hash);
      if (localProgress && localProgress.totalChunks === totalChunks) {
        console.log(`📦 使用本地进度记录：已上传 ${localProgress.uploadedChunks.length}/${totalChunks} 个分片`);
        uploadedChunksList = [...localProgress.uploadedChunks];
        isResuming = true;
        // 更新进度显示：显示断点续传提示
        const resumeProgress = Math.round((uploadedChunksList.length / totalChunks) * 90);
        onProgress(resumeProgress);
        updateProgress(file.name, resumeProgress, 'uploading', 
          `🔄 断点续传：从本地记录恢复，已上传 ${uploadedChunksList.length}/${totalChunks} 个分片`,
          `${uploadedChunksList.length}/${totalChunks} 分片`, true);
      }
    }

    // 初始化或更新进度记录
    saveUploadProgress({
      hash,
      filename: file.name,
      totalChunks,
      uploadedChunks: uploadedChunksList,
      fileSize: file.size,
      timestamp: Date.now()
    });

    // 显示初始进度
    const initialProgress = Math.round((uploadedChunksList.length / totalChunks) * 90);
    onProgress(Math.max(5, initialProgress));

    // 上传剩余的分片
    for (let i = 0; i < totalChunks; i++) {
      // 🔥 检查是否被暂停（使用 ref 获取最新值）
      if (pausedUploadsRef.current.has(hash)) {
        console.log('⏸️ 用户暂停上传');
        throw new Error('用户暂停上传');
      }

      // 🔥 跳过已上传的分片
      if (uploadedChunksList.includes(i)) {
        console.log(`⏭️ [跳过分片] ${i + 1}/${totalChunks} (索引: ${i})`);
        continue;
      }
      
      console.log(`📤 [上传分片] ${i + 1}/${totalChunks} (索引: ${i})`);

      const start = i * chunkSize;
      const end = Math.min(start + chunkSize, file.size);
      const chunk = file.slice(start, end);

      const formData = new FormData();
      formData.append('chunk', chunk);
      formData.append('hash', hash);
      formData.append('chunkIndex', i.toString());
      formData.append('totalChunks', totalChunks.toString());
      formData.append('filename', file.name);

      try {
        const uploadRes = await fileManagerAPI.uploadChunk(formData);
        
        // 更新已上传分片列表
        uploadedChunksList.push(i);
        updateUploadedChunk(hash, i);

        // 更新进度
        const progress = Math.round((uploadedChunksList.length / totalChunks) * 90);
        onProgress(Math.max(5, progress));
        
        // 更新进度信息，显示分片进度
        const chunkInfo = `${uploadedChunksList.length}/${totalChunks} 分片`;
        updateProgress(file.name, progress, 'uploading', 
          isResuming ? `🔄 续传中：${chunkInfo}` : `⏳ 上传中：${chunkInfo}`,
          chunkInfo, isResuming);

        // 后端直接返回数据，不是嵌套在 data 字段中
        const responseData = uploadRes.data || uploadRes;
        if (responseData.skipped) {
          console.log(`✓ 分片 ${i + 1}/${totalChunks} 已存在（跳过）`);
        } else {
          console.log(`✓ 分片 ${i + 1}/${totalChunks} 上传成功`);
        }
      } catch (error) {
        console.error(`✗ 分片 ${i + 1}/${totalChunks} 上传失败:`, error);
        throw error; // 抛出错误，触发重试机制
      }
    }

    // 合并切片
    console.log('🔗 开始合并分片...');
    try {
      const mergeResponse = await fileManagerAPI.mergeChunks({
        hash,
        filename: file.name,
        totalChunks,
        size: file.size,
        userId: 'user123',
        userName: '测试用户'
      });

      // 🔥 清理上传进度记录
      removeUploadProgress(hash);
      console.log('✅ 文件上传完成，已清理进度记录');

      // 如果是视频文件，提取封面
      if (file.type.startsWith('video/')) {
        try {
          const fileData = mergeResponse.data || mergeResponse;
          const videoUrl = fileData.url ? `http://localhost:3000${fileData.url}` : null;
          
          if (videoUrl) {
            console.log('🎬 开始为大文件视频提取封面:', file.name);
            // 从服务器URL提取封面
            const thumbnailBlob = await extractVideoThumbnailFromUrl(videoUrl);
            
            // 上传封面（标记为封面，不显示在文件列表中）
            const thumbnailFile = new File([thumbnailBlob], `thumb-${file.name}.jpg`, { type: 'image/jpeg' });
            const thumbnailFormData = new FormData();
            thumbnailFormData.append('files', thumbnailFile);
            thumbnailFormData.append('userId', 'user123');
            thumbnailFormData.append('userName', '测试用户');
            thumbnailFormData.append('isThumbnail', 'true'); // 标记为封面文件
            
            const thumbnailResponse = await fileManagerAPI.upload(thumbnailFormData);
            if (thumbnailResponse.success && thumbnailResponse.data && thumbnailResponse.data.length > 0) {
              const thumbnailUrl = thumbnailResponse.data[0].url;
              console.log('✅ 大文件视频封面上传成功:', thumbnailUrl);
              
              // 更新文件的thumbnailUrl
              const fileData = mergeResponse.data || mergeResponse;
              if (fileData._id) {
                try {
                  await fileManagerAPI.updateFileCover(fileData._id, { thumbnailUrl });
                  console.log('✅ 文件封面URL更新成功');
                } catch (error) {
                  console.warn('⚠️ 更新文件封面URL失败:', error);
                }
              }
            }
          }
        } catch (error) {
          console.warn('⚠️ 大文件视频封面提取/上传失败:', error);
        }
      }

      onProgress(100);
    } catch (error: unknown) {
      console.error('❌ 合并分片失败:', error);
      
      // 如果是缺少分片的错误，清除进度记录，让用户重新上传
      if (error instanceof Error && error.message && error.message.includes('缺少分片')) {
        console.log('🔄 检测到分片缺失，清除本地进度记录');
        removeUploadProgress(hash);
        throw new Error('文件分片不完整，请重新上传整个文件');
      }
      
      throw error;
    }
  };

  // 计算文件hash
  const calculateFileHash = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const spark = new SparkMD5.ArrayBuffer();
      const fileReader = new FileReader();
      const chunkSize = 2 * 1024 * 1024;
      let currentChunk = 0;
      const chunks = Math.ceil(file.size / chunkSize);

      fileReader.onload = (e) => {
        spark.append(e.target?.result as ArrayBuffer);
        currentChunk++;

        if (currentChunk < chunks) {
          loadNext();
        } else {
          resolve(spark.end());
        }
      };

      fileReader.onerror = () => reject(new Error('文件读取失败'));

      const loadNext = () => {
        const start = currentChunk * chunkSize;
        const end = Math.min(start + chunkSize, file.size);
        fileReader.readAsArrayBuffer(file.slice(start, end));
      };

      loadNext();
    });
  };

  // 更新上传进度
  const updateProgress = (
    filename: string, 
    progress?: number, 
    status?: 'uploading' | 'success' | 'error' | 'paused',
    message?: string,
    chunkInfo?: string,
    isResuming?: boolean
  ) => {
    setUploadProgress(prev => 
      prev.map(item => 
        item.filename === filename 
          ? { 
              ...item, 
              progress: progress !== undefined ? progress : item.progress, 
              status: status || item.status, 
              message,
              chunkInfo: chunkInfo !== undefined ? chunkInfo : item.chunkInfo,
              isResuming: isResuming !== undefined ? isResuming : item.isResuming
            }
          : item
      )
    );
  };

  // 暂停上传
  const pauseUpload = (hash: string) => {
    pausedUploadsRef.current.add(hash);
    console.log('⏸️ 暂停上传:', hash);
    console.log('🔍 当前暂停列表:', Array.from(pausedUploadsRef.current));
  };

  // 继续上传
  const resumeUpload = async (item: UploadProgress) => {
    if (!item.hash) return;
    
    // 从暂停列表中移除
    pausedUploadsRef.current.delete(item.hash);
    console.log('▶️ 恢复上传:', item.hash);
    console.log('🔍 当前暂停列表:', Array.from(pausedUploadsRef.current));

    // 更新状态为上传中
    updateProgress(item.filename, item.progress, 'uploading', '继续上传...');

    // 需要重新选择文件来继续上传
    console.log('📤 继续上传:', item.filename);
    console.log('💡 提示：请重新选择相同的文件来继续上传');
    alert(`请重新选择文件 "${item.filename}" 来继续上传`);
    fileInputRef.current?.click();
  };

  // 文件拖拽上传
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    const files = e.dataTransfer.files;
    if (files.length > 0) {
      handleFileUpload(files);
    }
  };

  // 选择/取消选择文件
  const toggleFileSelection = (fileId: string) => {
    const newSelected = new Set(selectedFiles);
    if (newSelected.has(fileId)) {
      newSelected.delete(fileId);
    } else {
      newSelected.add(fileId);
    }
    setSelectedFiles(newSelected);
  };

  // 全选/取消全选
  const toggleSelectAll = () => {
    if (selectedFiles.size === files.length) {
      setSelectedFiles(new Set());
    } else {
      setSelectedFiles(new Set(files.map(f => f._id)));
    }
  };

  // 下载文件
  const downloadFile = (file: FileItem) => {
    window.open(`http://localhost:3000/api/mqz/download/${file._id}`, '_blank');
  };

  // 批量下载
  const batchDownload = async () => {
    if (selectedFiles.size === 0) {
      alert('请先选择文件');
      return;
    }

    const ids = Array.from(selectedFiles);
    ids.forEach(id => {
      const file = files.find(f => f._id === id);
      if (file) downloadFile(file);
    });
  };

  // ✅ 删除文件（移至回收站）
  const deleteFile = async (fileId: string) => {
    if (!confirm('确定要删除这个文件吗？文件将移至回收站，可以恢复。')) return;

    try {
      await fileManagerAPI.moveToTrash(fileId, 'user123');
      alert('文件已移至回收站');
      loadFiles();
    } catch (error) {
      console.error('删除失败:', error);
      const message = error instanceof Error ? error.message : '删除失败';
      alert(message);
    }
  };

  // ✅ 批量删除（移至回收站）
  const batchDelete = async () => {
    if (selectedFiles.size === 0) {
      alert('请先选择文件');
      return;
    }

    if (!confirm(`确定要删除选中的 ${selectedFiles.size} 个文件吗？文件将移至回收站，可以恢复。`)) return;

    try {
      const fileIds = Array.from(selectedFiles);
      for (const fileId of fileIds) {
        await fileManagerAPI.moveToTrash(fileId, 'user123');
      }
      alert('文件已移至回收站');
      setSelectedFiles(new Set());
      loadFiles();
    } catch (error) {
      console.error('批量删除失败:', error);
      const message = error instanceof Error ? error.message : '批量删除失败';
      alert(message);
    }
  };

  // 创建分享
  const createShare = async () => {
    if (!shareModalFile) return;

    try {
      const response = await fileManagerAPI.createShare(shareModalFile._id, shareConfig);
      if (response.success) {
        setShareResult(response.data);
        loadFiles();
      }
    } catch (error) {
      console.error('创建分享失败:', error);
      const message = error instanceof Error ? error.message : '创建分享失败';
      alert(message);
    }
  };

  // 取消分享
  const cancelShare = async (fileId: string) => {
    try {
      await fileManagerAPI.cancelShare(fileId);
      alert('已取消分享');
      loadFiles();
    } catch (error) {
      console.error('取消分享失败:', error);
      const message = error instanceof Error ? error.message : '取消分享失败';
      alert(message);
    }
  };

  // 预览文件
  const previewFileHandler = (file: FileItem) => {
    setPreviewFile(file);
  };

  // 获取文件图标
  const getFileIcon = (category: string) => {
    const icons: Record<string, string> = {
      image: '🖼️',
      video: '🎬',
      audio: '🎵',
      document: '📄',
      other: '📦'
    };
    return icons[category] || '📦';
  };

  // 渲染文件卡片（网格视图）
  const renderFileCard = (file: FileItem) => (
    <div
      key={file._id}
      className={`relative rounded-lg transition-all cursor-pointer border ${
        selectedFiles.has(file._id)
          ? 'border-blue-500 dark:border-blue-400 shadow-lg'
          : isDark
            ? 'border-slate-700 hover:border-blue-400/80'
            : 'border-gray-200 hover:shadow-lg'
      } ${isDark ? 'bg-slate-950 text-slate-100' : 'bg-white text-gray-900 shadow-sm'} transition-colors`}
    >
      {/* 选择框 */}
      <div className="absolute top-2 left-2 z-10">
        <input
          type="checkbox"
          checked={selectedFiles.has(file._id)}
          onChange={() => toggleFileSelection(file._id)}
          className="w-5 h-5 cursor-pointer"
        />
      </div>

      {/* ✅ 收藏按钮 */}
      <button
        onClick={(e) => {
          e.stopPropagation();
          toggleFavorite(file._id, file.isFavorite || false);
        }}
        className="absolute top-2 right-2 z-10 text-2xl hover:scale-110 transition-transform"
        title={file.isFavorite ? '取消收藏' : '收藏'}
      >
        {file.isFavorite ? '⭐' : '☆'}
      </button>

      {/* 分享标识 */}
      {file.isShared && (
        <div className="absolute top-10 right-2 z-10 bg-green-500 text-white px-2 py-1 rounded text-xs">
          已分享
        </div>
      )}

      {/* 文件预览 */}
      <div 
        className="h-40 flex items-center justify-center bg-gray-100 dark:bg-slate-800 rounded-t-lg overflow-hidden relative transition-colors"
        onClick={() => previewFileHandler(file)}
      >
        {file.category === 'image' ? (
          <img 
            src={`http://localhost:3000${file.url}`} 
            alt={file.filename}
            className="w-full h-full object-cover"
          />
        ) : file.category === 'video' && file.thumbnailUrl ? (
          <img 
            src={`http://localhost:3000${file.thumbnailUrl}`} 
            alt={file.filename}
            className="w-full h-full object-cover"
            onError={(e) => {
              // 如果封面加载失败，显示默认图标
              const target = e.currentTarget;
              target.style.display = 'none';
              const parent = target.parentElement;
              if (parent) {
                const fallback = document.createElement('div');
                fallback.className = 'w-full h-full flex items-center justify-center';
                fallback.innerHTML = '<div class="text-6xl">🎬</div>';
                parent.appendChild(fallback);
              }
            }}
          />
        ) : (
          <div className="text-6xl">{getFileIcon(file.category)}</div>
        )}
      </div>

      {/* 文件信息 */}
      <div className={`p-3 transition-colors ${isDark ? 'bg-slate-950' : 'bg-white'}`}>
        <div className="font-medium text-sm truncate mb-1 text-gray-800 dark:text-slate-100" title={file.filename}>
          {file.filename}
        </div>
        <div className="text-xs text-gray-500 dark:text-slate-300 flex justify-between">
          <span>{file.sizeFormatted}</span>
          <span>👁️ {file.viewCount}</span>
        </div>
        <div className="text-xs text-gray-400 dark:text-slate-400 mt-1">
          {new Date(file.uploadedAt).toLocaleDateString()}
      </div>
      
        {/* 操作按钮 */}
        <div className="flex gap-1 mt-2 flex-wrap">
          <Permission code={ACTION_PERMISSION_CODES.FILE_DOWNLOAD}>
            <button
              onClick={() => downloadFile(file)}
              className="flex-1 px-2 py-1 bg-blue-500 text-white rounded text-xs hover:bg-blue-600"
            >
              下载
            </button>
          </Permission>
          <Permission code={ACTION_PERMISSION_CODES.FILE_SHARE}>
            <button
              onClick={() => setShareModalFile(file)}
              className="flex-1 px-2 py-1 bg-green-500 text-white rounded text-xs hover:bg-green-600"
            >
              分享
            </button>
          </Permission>
          <Permission code={ACTION_PERMISSION_CODES.FILE_DELETE}>
            <button
              onClick={() => deleteFile(file._id)}
              className="flex-1 px-2 py-1 bg-red-500 text-white rounded text-xs hover:bg-red-600"
            >
              删除
            </button>
          </Permission>
        </div>
      </div>
    </div>
  );

  // 渲染文件列表项（列表视图）
  const renderFileListItem = (file: FileItem) => (
    <tr
      key={file._id}
      className={`transition-colors ${
        selectedFiles.has(file._id)
          ? isDark
            ? 'bg-blue-500/15'
            : 'bg-blue-50'
          : isDark
            ? 'bg-slate-800/60'
            : ''
      } hover:bg-blue-100 dark:hover:bg-blue-500/20`}
    >
      <td className="px-4 py-3">
        <input
          type="checkbox"
          checked={selectedFiles.has(file._id)}
          onChange={() => toggleFileSelection(file._id)}
          className="w-4 h-4 cursor-pointer"
        />
      </td>
      <td className="px-4 py-3">
        <div className="flex items-center gap-2 text-gray-800 dark:text-slate-100">
          {/* ✅ 收藏按钮 */}
          <button
            onClick={(e) => {
              e.stopPropagation();
              toggleFavorite(file._id, file.isFavorite || false);
            }}
            className="text-xl hover:scale-110 transition-transform"
            title={file.isFavorite ? '取消收藏' : '收藏'}
          >
            {file.isFavorite ? '⭐' : '☆'}
          </button>
          <span className="text-2xl">{getFileIcon(file.category)}</span>
          <span 
            className="cursor-pointer hover:text-blue-600 dark:hover:text-blue-300"
            onClick={() => previewFileHandler(file)}
          >
            {file.filename}
          </span>
          {file.isShared && (
            <span className="text-xs bg-green-500 text-white px-2 py-0.5 rounded">已分享</span>
          )}
        </div>
      </td>
      <td className="px-4 py-3 text-sm text-gray-600 dark:text-slate-300">{file.sizeFormatted}</td>
      <td className="px-4 py-3 text-sm text-gray-600 dark:text-slate-300">{file.category}</td>
      <td className="px-4 py-3 text-sm text-gray-600 dark:text-slate-300">
        {new Date(file.uploadedAt).toLocaleString()}
      </td>
      <td className="px-4 py-3 text-sm text-gray-600 dark:text-slate-300">
        👁️ {file.viewCount} | ⬇️ {file.downloadCount}
      </td>
      <td className="px-4 py-3">
        <div className="flex gap-2">
          <Permission code={ACTION_PERMISSION_CODES.FILE_DOWNLOAD}>
            <button
              onClick={() => downloadFile(file)}
              className="px-3 py-1 bg-blue-500 text-white rounded text-sm hover:bg-blue-600"
            >
              下载
            </button>
          </Permission>
          <Permission code={ACTION_PERMISSION_CODES.FILE_SHARE}>
            <button
              onClick={() => setShareModalFile(file)}
              className="px-3 py-1 bg-green-500 text-white rounded text-sm hover:bg-green-600"
            >
              分享
            </button>
          </Permission>
          <Permission code={ACTION_PERMISSION_CODES.FILE_DELETE}>
            <button
              onClick={() => deleteFile(file._id)}
              className="px-3 py-1 bg-red-500 text-white rounded text-sm hover:bg-red-600"
            >
              删除
            </button>
          </Permission>
        </div>
      </td>
    </tr>
  );

  return (
    <div className="min-h-screen bg-gray-50 dark:bg-slate-950 p-6 transition-colors">
      {/* 页面标题 */}
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800 dark:text-slate-100">文件列表</h2>
      
        <div className="mt-3 p-3 bg-green-50 border border-green-200 rounded-lg">
          <p className="text-sm text-green-800">
            <strong>✅ 断点续传功能已启用：</strong>上传大于10MB的文件时，如果上传中断（刷新页面、关闭浏览器、网络中断），重新选择<strong className="font-bold">相同的文件</strong>上传，系统会自动检测已上传的分片并从断点继续上传。查看浏览器控制台可看到详细的续传日志。
          </p>
        </div>
      </div>

      {/* 工具栏 */}
      <div className="bg-white dark:bg-slate-900/85 rounded-lg shadow p-4 mb-6 transition-colors">
        <div className="flex flex-wrap items-center gap-4">
          {/* 上传按钮 */}
          <div>
            <input
              ref={fileInputRef}
              type="file"
              multiple
              className="hidden"
              onChange={(e) => e.target.files && handleFileUpload(e.target.files)}
            />
            <Permission code={ACTION_PERMISSION_CODES.FILE_UPLOAD}>
              <button
                onClick={() => fileInputRef.current?.click()}
                className="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center gap-2"
              >
                📤 上传文件
              </button>
            </Permission>
          </div>

          {/* 视图切换 */}
          <div className="flex gap-2">
            <button
              onClick={() => setViewMode('grid')}
              className={`px-3 py-2 rounded ${viewMode === 'grid' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}
            >
              网格
            </button>
            <button
              onClick={() => setViewMode('list')}
              className={`px-3 py-2 rounded ${viewMode === 'list' ? 'bg-blue-500 text-white' : 'bg-gray-200'}`}
            >
              列表
            </button>
          </div>


          {/* 批量操作 */}
          {selectedFiles.size > 0 && (
            <div className="flex gap-2">
              <span className="px-3 py-2 bg-gray-100 dark:bg-slate-800/70 dark:text-slate-100 rounded transition-colors">
                已选择 {selectedFiles.size} 个文件
              </span>
              <Permission code={ACTION_PERMISSION_CODES.FILE_DOWNLOAD}>
                <button
                  onClick={batchDownload}
                  className="px-3 py-2 bg-green-500 text-white rounded hover:bg-green-600"
                >
                  批量下载
                </button>
              </Permission>
              <Permission code={[ACTION_PERMISSION_CODES.FILE_DELETE, ACTION_PERMISSION_CODES.FILE_BATCH_DELETE]} mode="any">
                <button
                  onClick={batchDelete}
                  className="px-3 py-2 bg-red-500 text-white rounded hover:bg-red-600"
                >
                  批量删除
                </button>
              </Permission>
              <button
                onClick={() => setSelectedFiles(new Set())}
                className="px-3 py-2 bg-gray-500 text-white rounded hover:bg-gray-600"
              >
                取消选择
              </button>
            </div>
          )}

          {/* 搜索 */}
          <div className="flex-1 min-w-[200px]">
            <input
              type="text"
              placeholder="搜索文件名..."
              value={keyword}
              onChange={(e) => setKeyword(e.target.value)}
              className="w-full px-4 py-2 border border-gray-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-slate-800 dark:text-slate-100 transition-colors"
            />
          </div>
        </div>
      </div>

      {/* 分类筛选 */}
      <div className="flex gap-2 mb-6 overflow-x-auto">
        {FILE_CATEGORIES.map(cat => (
          <button
            key={cat.value}
            onClick={() => setSelectedCategory(cat.value)}
            className={`px-4 py-2 rounded-lg whitespace-nowrap transition-colors ${
              selectedCategory === cat.value
                ? 'bg-blue-500 text-white'
                : 'bg-white text-gray-700 hover:bg-gray-100 dark:bg-slate-800 dark:text-slate-100 dark:hover:bg-slate-700/80'
            }`}
          >
            {cat.icon} {cat.label}
          </button>
        ))}
      </div>

      {/* 上传进度 */}
      {uploadProgress.length > 0 && (
        <div className="bg-white dark:bg-slate-900/85 rounded-lg shadow p-4 mb-6 transition-colors">
          <h3 className="font-semibold mb-3">上传进度</h3>
          {uploadProgress.map((item, index) => (
            <div key={index} className="mb-3">
              <div className="flex justify-between items-center text-sm mb-1">
                <div className="flex-1">
                  <div className="flex items-center gap-2">
                    <span>{item.filename}</span>
                    {item.isResuming && (
                      <span className="px-2 py-0.5 bg-blue-100 text-blue-700 rounded text-xs font-medium">
                        🔄 断点续传
                      </span>
                    )}
                    {item.chunkInfo && (
                      <span className="px-2 py-0.5 bg-gray-100 text-gray-600 rounded text-xs">
                        {item.chunkInfo}
                      </span>
                    )}
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <span className={
                    item.status === 'success' ? 'text-green-500' :
                    item.status === 'error' ? 'text-red-500' :
                    item.status === 'paused' ? 'text-orange-500' :
                    'text-blue-500'
                  }>
                    {item.status === 'success' ? '✓ ' : 
                     item.status === 'error' ? '✗ ' : 
                     item.status === 'paused' ? '⏸️ ' : '⏳ '}
                    {item.progress}%
                  </span>
                  {/* 暂停/继续按钮 */}
                  {item.hash && item.status === 'uploading' && (
                    <button
                      onClick={() => pauseUpload(item.hash!)}
                      className="px-2 py-1 text-xs bg-orange-500 text-white rounded hover:bg-orange-600"
                      title="暂停上传"
                    >
                      ⏸️ 暂停
                    </button>
                  )}
                  {item.hash && item.status === 'paused' && (
                    <button
                      onClick={() => resumeUpload(item)}
                      className="px-2 py-1 text-xs bg-green-500 text-white rounded hover:bg-green-600"
                      title="继续上传"
                    >
                      ▶️ 继续
                    </button>
                  )}
                </div>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div
                  className={`h-2 rounded-full transition-all ${
                    item.status === 'success' ? 'bg-green-500' :
                    item.status === 'error' ? 'bg-red-500' :
                    item.status === 'paused' ? 'bg-orange-500' :
                    'bg-blue-500'
                  }`}
                  style={{ width: `${item.progress}%` }}
                />
              </div>
              {item.message && (
                <div className="text-xs text-gray-500 mt-1">{item.message}</div>
              )}
            </div>
          ))}
        </div>
      )}

      {/* 拖拽上传区域 */}
      <div
        ref={dragRef}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
        className="border-2 border-dashed border-gray-300 dark:border-slate-600 rounded-lg p-8 mb-6 text-center hover:border-blue-500 dark:hover:border-blue-400 transition-colors bg-white dark:bg-slate-900/70"
      >
        <div className="text-4xl mb-2">📁</div>
        <div className="text-gray-600">拖拽文件到这里上传</div>
        <div className="text-sm text-gray-400 mt-1">支持大文件切片上传（最大500MB）</div>
      </div>

      {/* 文件列表 */}
      {loading ? (
        <div className="text-center py-12">
          <div className="text-4xl mb-2">⏳</div>
          <div className="text-gray-600">加载中...</div>
        </div>
      ) : files.length === 0 ? (
        <div className="text-center py-12 bg-white dark:bg-slate-900/85 rounded-lg transition-colors">
          <div className="text-4xl mb-2">📭</div>
          <div className="text-gray-600">暂无文件</div>
        </div>
      ) : (
        <>
          {/* 网格视图 */}
          {viewMode === 'grid' && (
            <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
              {files.map(renderFileCard)}
            </div>
          )}

          {/* 列表视图 */}
          {viewMode === 'list' && (
            <div className="bg-white dark:bg-slate-900/80 rounded-lg shadow overflow-hidden transition-colors">
              <table className="w-full">
                <thead className="bg-gray-50 dark:bg-slate-900 text-gray-700 dark:text-slate-100 transition-colors">
                  <tr>
                    <th className="px-4 py-3 text-left">
                      <input
                        type="checkbox"
                        checked={files.length > 0 && selectedFiles.size === files.length}
                        onChange={toggleSelectAll}
                        className="w-4 h-4 cursor-pointer"
                      />
                    </th>
                    <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                      文件名
                    </th>
                    <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                      大小
                    </th>
                    <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                      类型
                    </th>
                    <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                      上传时间
                    </th>
                    <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                      统计
                    </th>
                    <th className="px-4 py-3 text-left text-sm font-semibold text-gray-700">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-200">
                  {files.map(renderFileListItem)}
                </tbody>
              </table>
            </div>
          )}
        </>
      )}

      {/* 文件预览模态框 */}
      {previewFile && (
        <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4">
          <div className={`bg-white dark:bg-slate-900 rounded-lg ${previewFile.category === 'video' ? 'max-w-6xl' : 'max-w-4xl'} w-full max-h-[90vh] overflow-auto transition-colors`}>
            <div className="p-4 border-b border-gray-200 dark:border-slate-700 flex justify-between items-center">
              <h3 className="font-semibold text-lg">{previewFile.filename}</h3>
              <button
                onClick={() => setPreviewFile(null)}
                className="text-2xl hover:text-red-500"
              >
                ×
              </button>
            </div>
            <div className="p-4">
              {previewFile.category === 'image' && (
                <img
                  src={`http://localhost:3000${previewFile.url}`}
                  alt={previewFile.filename}
                  className="w-full h-auto"
                />
              )}
              {previewFile.category === 'video' && (
                <div className="w-full bg-black flex items-center justify-center">
                  <video
                    src={`http://localhost:3000${previewFile.url}`}
                    controls
                    className="w-full max-h-[70vh] object-contain"
                    style={{ maxWidth: '100%' }}
                  />
                </div>
              )}
              {previewFile.category === 'audio' && (
                <audio
                  src={`http://localhost:3000${previewFile.url}`}
                  controls
                  className="w-full"
                />
              )}
              {previewFile.category === 'document' && previewFile.extension === '.pdf' && (
                <iframe
                  src={`http://localhost:3000${previewFile.url}`}
                  className="w-full h-[600px]"
                  title={previewFile.filename}
                />
              )}
              {previewFile.category === 'other' && (
                <div className="text-center py-12">
                  <div className="text-6xl mb-4">{getFileIcon(previewFile.category)}</div>
                  <p className="text-gray-600">此文件类型不支持预览</p>
                  <button
                    onClick={() => downloadFile(previewFile)}
                    className="mt-4 px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                  >
                    下载文件
                  </button>
                </div>
              )}
            </div>
            <div className="p-4 border-t bg-gray-50 dark:bg-slate-800/80 border-gray-200 dark:border-slate-700 transition-colors">
              <div className="grid grid-cols-2 gap-4 text-sm text-gray-700 dark:text-slate-200">
                <div><span className="text-gray-600 dark:text-slate-400">大小：</span>{previewFile.sizeFormatted}</div>
                <div><span className="text-gray-600 dark:text-slate-400">类型：</span>{previewFile.mimetype}</div>
                <div><span className="text-gray-600 dark:text-slate-400">上传时间：</span>{new Date(previewFile.uploadedAt).toLocaleString()}</div>
                <div><span className="text-gray-600 dark:text-slate-400">上传者：</span>{previewFile.uploadedByName}</div>
                <div><span className="text-gray-600 dark:text-slate-400">查看次数：</span>{previewFile.viewCount}</div>
                <div><span className="text-gray-600 dark:text-slate-400">下载次数：</span>{previewFile.downloadCount}</div>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 分享设置模态框 */}
      {shareModalFile && !shareResult && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-slate-900 rounded-lg max-w-md w-full transition-colors">
            <div className="p-4 border-b border-gray-200 dark:border-slate-700 flex justify-between items-center">
              <h3 className="font-semibold text-lg">分享文件</h3>
              <button
                onClick={() => {
                  setShareModalFile(null);
                  setShareResult(null);
                }}
                className="text-2xl hover:text-red-500"
              >
                ×
              </button>
            </div>
            <div className="p-4 text-gray-700 dark:text-slate-200">
              <div className="mb-4">
                <div className="font-medium text-sm text-gray-700 dark:text-slate-300 mb-2">文件名</div>
                <div className="text-sm text-gray-600 dark:text-slate-200">{shareModalFile.filename}</div>
              </div>

              {shareModalFile.isShared ? (
                <div className="bg-yellow-50 dark:bg-amber-500/20 border border-yellow-200 dark:border-amber-400/40 rounded p-3 mb-4">
                  <div className="text-sm text-yellow-800 dark:text-amber-200 mb-2">此文件已经分享</div>
                  <button
                    onClick={() => {
                      cancelShare(shareModalFile._id);
                      setShareModalFile(null);
                    }}
                    className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
                  >
                    取消分享
                  </button>
                </div>
              ) : (
                <>
                  <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 dark:text-slate-300 mb-2">
                      有效期（天）
                    </label>
                    <input
                      type="number"
                      value={shareConfig.expireDays}
                      onChange={(e) => setShareConfig({...shareConfig, expireDays: parseInt(e.target.value)})}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-slate-800 dark:text-slate-100"
                      min="1"
                      max="30"
                    />
                  </div>

                  <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 dark:text-slate-300 mb-2">
                      分享密码（可选）
                    </label>
                    <input
                      type="text"
                      value={shareConfig.password}
                      onChange={(e) => setShareConfig({...shareConfig, password: e.target.value})}
                      placeholder="留空则不设置密码"
                      className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-slate-800 dark:text-slate-100"
                    />
                  </div>

                  <div className="mb-4">
                    <label className="block text-sm font-medium text-gray-700 dark:text-slate-300 mb-2">
                      下载次数限制（可选）
                    </label>
                    <input
                      type="number"
                      value={shareConfig.downloadLimit}
                      onChange={(e) => setShareConfig({...shareConfig, downloadLimit: parseInt(e.target.value)})}
                      placeholder="0 表示不限制"
                      className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-slate-800 dark:text-slate-100"
                      min="0"
                    />
                  </div>

                  <button
                    onClick={createShare}
                    className="w-full px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                  >
                    创建分享链接
                  </button>
                </>
              )}
            </div>
          </div>
        </div>
      )}

      {/* 分享结果模态框 */}
      {shareResult && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-slate-900 rounded-lg max-w-md w-full transition-colors">
            <div className="p-4 border-b border-gray-200 dark:border-slate-700 flex justify-between items-center">
              <h3 className="font-semibold text-lg">分享链接已创建</h3>
              <button
                onClick={() => {
                  setShareResult(null);
                  setShareModalFile(null);
                }}
                className="text-2xl hover:text-red-500"
              >
                ×
              </button>
            </div>
            <div className="p-4 text-gray-700 dark:text-slate-200">
              <div className="bg-green-50 dark:bg-emerald-500/20 border border-green-200 dark:border-emerald-400/40 rounded p-4 mb-4">
                <div className="text-sm text-gray-700 dark:text-emerald-100 mb-2 font-semibold">✅ 分享链接已创建</div>
                <div className="bg-white dark:bg-slate-900/80 p-3 rounded border border-gray-200 dark:border-slate-600 break-all text-sm font-mono mb-3">
                  {shareResult.shareUrl}
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(shareResult.shareUrl);
                      alert('✅ 分享链接已复制到剪贴板');
                    }}
                    className="flex-1 px-3 py-2 bg-blue-500 text-white rounded text-sm hover:bg-blue-600"
                  >
                    📋 复制链接
                  </button>
                  <button
                    onClick={() => {
                      window.open(shareResult.shareUrl, '_blank');
                    }}
                    className="flex-1 px-3 py-2 bg-green-500 text-white rounded text-sm hover:bg-green-600"
                  >
                    🔗 打开链接
                  </button>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-4 text-sm mb-4">
                <div>
                  <span className="text-gray-600 dark:text-slate-300">分享码：</span>
                  <div className="mt-1">
                    <span className="font-mono font-semibold text-lg">{shareResult.shareCode}</span>
                    <button
                      onClick={() => {
                        navigator.clipboard.writeText(shareResult.shareCode);
                        alert('分享码已复制');
                      }}
                      className="ml-2 text-blue-500 hover:text-blue-700 text-xs"
                    >
                      复制
                    </button>
                  </div>
                </div>
                {shareResult.hasPassword && (
                  <div>
                    <span className="text-gray-600 dark:text-slate-300">密码保护：</span>
                    <div className="mt-1 text-green-600 dark:text-emerald-200 font-semibold">🔒 已启用</div>
                  </div>
                )}
                <div className="col-span-2 pt-2 border-t border-gray-200">
                  <span className="text-gray-600 dark:text-slate-300">过期时间：</span>
                  <span className="font-semibold dark:text-slate-100">{new Date(shareResult.expireAt).toLocaleString('zh-CN')}</span>
                </div>
              </div>

              <div className="bg-blue-50 dark:bg-blue-500/20 border border-blue-200 dark:border-blue-400/40 rounded p-3 text-xs text-blue-800 dark:text-blue-100">
                <p className="font-semibold mb-1">💡 使用提示：</p>
                <ul className="list-disc list-inside space-y-1">
                  <li>将分享链接发送给他人即可访问文件</li>
                  {shareResult.hasPassword && <li>访问时需要输入分享密码</li>}
                  <li>分享链接将在过期时间后失效</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default FileManager

